import numpy as np

from util.util_ris_pattern_2 import point_2_phase, phase_2_pattern, phase_2_pattern_xyz, eps, \
    phase_2_bit, phaseBit_2_deg, phase_2_pattern_xyz_fft
from util.util_analysis_plane import get_peaks, get_peak_nth

# ============================================= 天线相关计算 =======================================
def phases_rad_2_bit(phaseRads, bit_num):
    """ 码阵转bit """
    phaseBits = []
    for phaseRad in phaseRads:
        phaseBit, phaseDeg = phase_2_bit(phaseRad, bit_num)
        phaseBits.append(phaseBit)
    return phaseBits

def traces_2_phaseRads(traces):
    """ 轨迹计算方向图: traces算phase """
    phaseRads = []
    for trace in traces:
        theta0 = trace[0]
        phi0 = trace[1]
        phaseRad = point_2_phase(theta0, phi0)
        phaseRad = np.rad2deg(phaseRad)
        phaseRads.append(phaseRad)
    return phaseRads


# pattern 计算 peaks
def pattern_2_peaks(pattern):
    # pattern 转dB
    pattern_dbw = 20 * np.log10(np.abs(pattern) / np.max(np.max(np.abs(pattern))) + eps)
    # pattern找峰值
    peaks = get_peaks(pattern_dbw)
    return peaks


# 计算phase的方向图
def phaseBit_2_pattern(phaseBit, bit_num):
    phaseBitDeg = phaseBit_2_deg(phaseBit, bit_num)
    phaseBitRad = np.deg2rad(phaseBitDeg)
    # pattern_xyz, x, y, z = phase_2_pattern_xyz(phaseBitRad)
    pattern_xyz, x, y = phase_2_pattern_xyz_fft(phaseBitRad)  # FFT法计算, 快速
    # return np.abs(pattern_xyz), x, y
    return pattern_xyz, x, y


def phaseBit_2_pattern_point(phaseBit, bit_num):
    pattern, x, y = phaseBit_2_pattern(phaseBit, bit_num)
    peaks = pattern_2_peaks(pattern)
    point = peaks[0]
    psll = get_peak_nth(peaks, 1)
    return pattern, point, psll